package com.softer.wxzj.service.impl;

/**
 * @author Niu
 * @create 2019/5/21 - 10:03 - 星期二
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.util.FlowUpdateAuditUtil;
import com.softer.wxzj.common.logic.CalculateAmount;
import com.softer.wxzj.common.logic.DepReqLogic;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseOwnerInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业主信息
 *
 * @author
 */
@Service
public class BaseOwnerInfoServiceImpl implements BaseOwnerInfoService {
    @Autowired
    private BaseOwnerInfoMapper baseOwnerInfoMapper;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private FlowUpdateAuditUtil flowUpdateAuditUtil;
    @Autowired
    private ModifyUtilList modifyUtilList;
    @Autowired
    private ModifyUtil<BaseOwnerInfo> modifyUtil;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private CombineEntityUtil<BaseOwnerInfo> combineEntityUtil;
    @Autowired
    private OperUtil operUtil;
    @Autowired
    TransReqMapper transReqMapper;
    @Autowired
    private ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private DicContentMapper dicContentMapper;
    @Autowired
    private DepModeInfoMapper depModeInfoMapper;
    @Autowired
    private CalculateAmount calculateAmount;
    @Autowired
    private AccTransactionLogMapper accTransactionLogMapper;
    @Autowired
    private AccKeepAccountServiceImpl accKeepAccountService;
    @Autowired
    private DepReqLogic depReqLogic;
    @Autowired
    private SplitMergeReqDetailMapper splitMergeReqDetailMapper;
    @Autowired
    private FileServiceImpl fileService;

    /**
     * 询当前登录账户管理下的小区业主（非保存状态和删除状态）的信息列表 分页
     *
     * @param page
     * @return
     */
    @Override
    public PageInfo<BaseOwnerInfoList> getBaseOwnerInfoList(Page page, BaseOwnerInfoList baseOwnerInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOwnerInfoList> list = baseOwnerInfoMapper.getBaseOwnerInfoList(baseOwnerInfo);
        for (BaseOwnerInfoList b : list) {
            //缴存
            b.setFirstDue(accTransactionLogMapper.selectMoneyDepAll(b.getId()).subtract(accTransactionLogMapper.selectMoneyReqAll(b.getId())));
            //使用
            b.setExpMoney(accTransactionLogMapper.selectExpByHouseId(b.getId()));
            //有效金额   账户余额-冻结金额
            b.setUseMoney(b.getFunBal().subtract(b.getAccountFrozen()));
        }
        PageInfo<BaseOwnerInfoList> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据业主id查询业主信息
     *
     * @param id
     * @return
     */
    @Override
    public BaseOwnerInfo getBaseOwnerInfoModule(String id) {
        return baseOwnerInfoMapper.getBaseOwnerInfoModule(id);
    }

    @Override
    public CommonResult insert(BaseOwnerInfo baseOwnerInfo) {
        return null;
    }

    @Override
    public CommonResult update(BaseOwnerInfo baseOwnerInfo) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(baseOwnerInfo.getAccNo());
        if (!baseHouseInfo.getDueState().equals(NumStrEnum.FOUR.getNum()) && null != baseHouseInfo.getDueState()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋已交存不可以修改业主");
        } else if (baseHouseInfo.getFlowInProgress() != null && !NumStrEnum.ZERO.getNum().equals(baseHouseInfo.getFlowInProgress())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋存在在途业务不可以修改业主");
        }
        //查询原始数据
        BaseOwnerInfo info = baseOwnerInfoMapper.selectBaseOwnerInfo(baseOwnerInfo.getId());
        //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
        BaseOwnerInfo buildInfo = combineEntityUtil.combineEntity(baseOwnerInfo, info);
        //注意是全表更新
        int num = baseOwnerInfoMapper.updateById(buildInfo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return CommonResult.ResponseResult(num, baseOwnerInfo.getId());
    }

    /**
     * 修改业主
     *
     * @param baseOwnerInfoList 业主/共有人集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult updateOwnerAndHouse(List<BaseOwnerInfo> baseOwnerInfoList) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(baseOwnerInfoList.get(0).getAccNo());
        if (!baseHouseInfo.getDueState().equals(NumStrEnum.FOUR.getNum()) && null != baseHouseInfo.getDueState()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋已交存不可以修改业主");
        } else if (baseHouseInfo.getFlowInProgress() != null && !NumStrEnum.ZERO.getNum().equals(baseHouseInfo.getFlowInProgress())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋存在在途业务不可以修改业主");
        }
        for (BaseOwnerInfo baseOwnerInfo : baseOwnerInfoList) {
            if (String.valueOf(NumberEnum.ZERO.getNum()).equals(baseOwnerInfo.getInfoType())) {
                //如果修改的是业主，则同时修改房间表
                updateHouse(baseOwnerInfo);
            }
            //修改业主
            update(baseOwnerInfo);
            //处理图片修改
            CommonResult result = fileService.updateFile(baseOwnerInfo.getFileTypeList(), baseOwnerInfo.getId());
            if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
            }
            //关联附房
            CommonResult houseResult = insertOrUpdateToView(baseOwnerInfo.getBaseOwnerInfoList());
            if (ShiroResultEnum.FAIL.getCode() == houseResult.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), houseResult.getMessage());
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 新增业主前，查询业主房间的信息
     *
     * @param houseId 房间Id
     * @return 结果
     */
    @Override
    public BaseOwnerInfoMap getOwnerHouseInfo(String houseId) {
        return baseOwnerInfoMapper.getOwnerHouseInfo(houseId);
    }

    /**
     * 删除业主
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult delete(String id) {
        if (StringUtils.isBlank(id)) {
            return CommonResult.ResponseResult(0, "请先选择业主再删除");
        }
        BaseOwnerInfo base = baseOwnerInfoMapper.getInfo(id);
        if (NumStrEnum.ONE.getNum().equals(base.getInfoType())) {
            baseOwnerInfoMapper.delete(id);
        } else {
            //查看是否审核数据
            int count = flowInstanceMapper.getCountByBusinessId(id);
            if (count > 0) {
                return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在审核中信息，不允许删除！");
            }
            //主房是否发生过缴存
            BaseOwnerInfo info = baseOwnerInfoMapper.getInfoById(id);
            int countDep = accTransactionLogMapper.selectDepNom(info.getId());
            if (countDep > 0) {
                return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在缴存业务，不允许删除！");
            }
            //如果info是主房 附房是否发生过缴存
            if (NumStrEnum.ZERO.getNum().equals(info.getIsAffiliated())) {
                //查询附房数据
                List<BaseHouseInfo> affiliatedInfo = baseHouseInfoMapper.selectMain(info.getId());
                for (BaseHouseInfo b : affiliatedInfo) {
                    int countAffiliatedDep = accTransactionLogMapper.selectDepNom(b.getId());
                    if (countAffiliatedDep > 0) {
                        return new CommonResult(ShiroResultEnum.FAIL.getCode(), "附房已存在缴存业务，不允许删除！");
                    }
                }
            }
            List<BaseOwnerInfo> affiliatedList = null;
            if (null != info && NumStrEnum.ZERO.getNum().equals(info.getInfoType()) && NumStrEnum.ZERO.getNum().equals(info.getIsAffiliated())) {
                //根据业主id查询附房业主集合
                affiliatedList = baseOwnerInfoMapper.getListByOwnerId(id);
                //判断附房是否有审核中的信息
                if (!affiliatedList.isEmpty()) {
                    for (BaseOwnerInfo baseOwnerInfo : affiliatedList) {
                        count = flowInstanceMapper.getCountByBusinessId(baseOwnerInfo.getId());
                        if (count > 0) {
                            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "附房存在审核中信息，不允许删除！");
                        }
                    }
                }
            }
            //业主删除共有人信息、清理房间信息
            if (null != info && NumStrEnum.ZERO.getNum().equals(info.getInfoType())) {
//                //删除共有人
//
                //存在附房则删除附房业主、清理附房房间信息
                if (null != affiliatedList && !affiliatedList.isEmpty()) {
                    for (BaseOwnerInfo affiliated : affiliatedList) {
                        baseOwnerInfoMapper.delete(affiliated.getId());
                        clearHouse(affiliated.getAccNo());
                    }
                }
                //清理主房房间信息
                clearHouse(info.getAccNo());
            }
            //看业主是否使用过
            int num = accTransactionLogMapper.selectByOwnerIdAll(id);
            if (num == 0) {
                if (0 == baseModifyReqMapper.selectCountByBusinessId(id)) {
                    baseOwnerInfoMapper.deleteCurrentByAccNo(info.getAccNo());
                } else {
                    baseOwnerInfoMapper.updatStateByOwner(base.getOwnerNo());
                }
            } else {
                baseOwnerInfoMapper.updatStateByOwner(base.getOwnerNo());
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 设置房间为未绑定业主状态
     *
     * @param accNo
     * @return
     */
    private int clearHouse(String accNo) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(accNo);
        if (!baseHouseInfo.getDueState().equals(NumStrEnum.FOUR.getNum()) && null != baseHouseInfo.getDueState()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋已交存不可以修改或删除业主");
        } else if (baseHouseInfo.getFlowInProgress() != null && !NumStrEnum.ZERO.getNum().equals(baseHouseInfo.getFlowInProgress())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋存在在途业务不可以修改或删除业主");
        }
        BaseHouseInfo houseInfo = new BaseHouseInfo();
        houseInfo.setId(accNo);
        houseInfo.setOwnerState(NumStrEnum.ZERO.getNum());
        houseInfo.setState(NumStrEnum.ZERO.getNum());
        houseInfo.setMainHouseId("");
        houseInfo.setIsAffiliated(NumStrEnum.ZERO.getNum());
        return baseHouseInfoMapper.update(houseInfo);
    }

    @Override
    public PageInfo<BaseOwnerInfo> getList(Page page, BaseOwnerInfo baseOwnerInfo) {
        return null;
    }

    @Override
    public PageInfo<BaseOwnerInfoList> getList(Page page, BaseOwnerInfoList baseOwnerInfo) {
        //赋值区域,重要
        baseOwnerInfo.setZoneCode(operUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOwnerInfoList> list;
        if (baseOwnerInfo.getNo().equals(NumStrEnum.ONE.getNum())) {
            list = baseOwnerInfoMapper.getNewListDep(baseOwnerInfo);
        } else {
            list = baseOwnerInfoMapper.getNewList(baseOwnerInfo);
        }
        String address;
        for (int i = 0; i < list.size(); i++) {
            list.get(i).getZoneCode();
            String zoneCode = StringUtils.substring(list.get(i).getZoneCode(), 0, 6);
            String code = zoneCodeMapper.getZoneName(zoneCode);
            if (StringUtils.isBlank(list.get(i).getSubRegionName())) {
                list.get(i).setSubRegionName("");
            }
            address = code + list.get(i).getRegionName() + list.get(i).getSubRegionName() + list.get(i).getBuildName() + list.get(i).getCellName() + list.get(i).getRoomName();
            list.get(i).setAddress(address);
        }
        PageInfo<BaseOwnerInfoList> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public CommonResult bindSubHouse(@RequestBody List<BaseOwnerInfo> baseOwnerInfoList, String houseId, String subHouseId) {
        int i = NumberEnum.ZERO.getNum();
        //根据房屋id查询所有业主集合
        List<BaseOwnerInfo> infoList = baseOwnerInfoMapper.getInfoListByHouseId(houseId);
        //根据房屋id查询对应业主信息
        String[] idList = subHouseId.split(",");
        for (BaseOwnerInfo info : baseOwnerInfoList) {
            info.setCreateTime(DateUtils.getNow());
            info.setCreater(ShiroUserUtil.getUserName());
            //0业主  1共有人
            if (String.valueOf(NumberEnum.ZERO.getNum()).equals(info.getInfoType())) {
                con:
                for (String hId : idList) {
                    info.setAccNo(hId);
                    for (BaseOwnerInfo baseOwnerInfo : infoList) {
                        if (hId.equals(baseOwnerInfo.getAccNo())) {
                            //存在业主信息  更新业主信息
                            info.setId(baseOwnerInfo.getId());
                            i = baseOwnerInfoMapper.updateById(info);
                            continue con;
                        }
                    }
                    //不存在业主信息  新增业主信息
                    info.setId(UUIDUtil.getUUID());
                    i = baseOwnerInfoMapper.insert(info);
                }
            } else if (String.valueOf(NumberEnum.ONE.getNum()).equals(info.getInfoType())) {
                info.setId(UUIDUtil.getUUID());
                info.setAccNo(houseId);
                i = baseOwnerInfoMapper.insert(info);
            }
        }
        return CommonResult.ResponseResult(i);
    }

    @Override
    public List<BaseOwnerInfo> getSubHouseList(String accNo) {
        return baseOwnerInfoMapper.getSubHouseList(accNo);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public synchronized CommonResult insertOrUpdateToView(List<BaseOwnerInfo> baseOwnerInfoList) {
        if (null == baseOwnerInfoList) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "请选择要修改或要添加的业主");
        }
        for (BaseOwnerInfo b : baseOwnerInfoList) {
            if (StringUtils.isBlank(b.getId())) {
                if (null != baseOwnerInfoMapper.getInfoByAccNo(b.getAccNo())) {
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "请刷新页面");
                }
            }
        }
        int num = NumberEnum.ZERO.getNum();
        //查询主业主信息
        BaseOwnerInfo info = baseOwnerInfoMapper.getInfoById(baseOwnerInfoList.get(0).getOwnerId());
        for (BaseOwnerInfo baseOwnerInfo : baseOwnerInfoList) {
            baseOwnerInfo.setCertType(info.getCertType());
            baseOwnerInfo.setCertNo(info.getCertNo());
            baseOwnerInfo.setPhone(info.getPhone());
            baseOwnerInfo.setState(NumStrEnum.ONE.getNum());
            baseOwnerInfo.setName(info.getName());
            baseOwnerInfo.setPurchaseDate(baseOwnerInfo.getPurchaseDate());
            baseOwnerInfo.setOwnerId(baseOwnerInfoList.get(0).getOwnerId());
            baseOwnerInfo.setIsAffiliated(NumStrEnum.ONE.getNum());
            if (StringUtils.isBlank(baseOwnerInfo.getId())) {
                baseOwnerInfo.setOwnerNo(ownerNo(baseOwnerInfo.getAccNo()));
                baseOwnerInfo.setId(UUIDUtil.getUUID());
                baseOwnerInfo.setCreater(ShiroUserUtil.getUserName());
                //新增业主时 删除原业主信息
                baseOwnerInfoMapper.deleteCurrentByAccNo(baseOwnerInfo.getAccNo());
            } else {
                BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(baseOwnerInfo.getAccNo());
                if (null != baseHouseInfo.getDueState() && !baseHouseInfo.getDueState().equals(NumStrEnum.FOUR.getNum())) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋已交存不可以修改业主");
                }
                if (baseHouseInfo.getFlowInProgress() != null && !NumStrEnum.ZERO.getNum().equals(baseHouseInfo.getFlowInProgress())) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋存在在途业务不可以修改业主");
                }
                baseOwnerInfo.setOwnerNo(info.getOwnerNo());
            }
            if (StringUtils.isBlank(baseOwnerInfo.getInfoType())) {
                baseOwnerInfo.setInfoType(String.valueOf(NumberEnum.ZERO.getNum()));
            }
            num = baseOwnerInfoMapper.insertOrUpdate(baseOwnerInfo);
            //查询房屋信息  用于计算初交应交
            BaseHouseInfo houseInfo = baseHouseInfoMapper.getInfo(baseOwnerInfo.getAccNo());
            //更新房屋信息
            BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
            baseHouseInfo.setId(baseOwnerInfo.getAccNo());
            baseHouseInfo.setPrice(baseOwnerInfo.getPrice());
            baseHouseInfo.setStruArea(baseOwnerInfo.getStruArea());
            baseHouseInfo.setPurchaseDate(baseOwnerInfo.getPurchaseDate());
            baseHouseInfo.setOwnerState(NumStrEnum.ONE.getNum());
            baseHouseInfo.setDueState(NumStrEnum.FOUR.getNum());
            baseHouseInfo.setState(NumStrEnum.ONE.getNum());
            baseHouseInfo.setMainHouseId(info.getAccNo());
            baseHouseInfo.setIsAffiliated(NumStrEnum.ONE.getNum());
            houseInfo.setPrice(baseOwnerInfo.getPrice());
            baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(houseInfo));
            baseHouseInfoMapper.update(baseHouseInfo);
        }
        return CommonResult.ResponseResult(num);
    }

    @Override
    public CommonResult deleteToView(String idList) {
        Arrays.asList(idList.split(",")).forEach(id -> {
            BaseOwnerInfo info = baseOwnerInfoMapper.getInfo(id);
            //删除业主
            baseOwnerInfoMapper.delete(id);
            //清楚房间面积
            baseHouseInfoMapper.clearStruArea(info.getAccNo());
        });
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    @Override
    public BaseOwnerInfo selectOwner(String houseId) {
        BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(houseId);
        baseOwnerInfo.setCertTypeName(dicContentMapper.selectName(baseOwnerInfo.getCertType()));
        return baseOwnerInfo;
    }

    @Override
    public List<BaseOwnerInfo> selectOwnerByOwnerNo(String ownerNo) {
        return baseOwnerInfoMapper.selectOwnerByOwnerNo(ownerNo);
    }

    @Override
    public List<BaseOwnerInfo> selectNewowner(String qId) {
        TransReq transReq = transReqMapper.getInfo(qId);
        List<BaseOwnerInfo> baseOwnerInfo = baseOwnerInfoMapper.selectNewOwnerByOwnerNo(qId);
        baseOwnerInfo.get(0).setTransRemark(transReq.getRemark());
        baseOwnerInfo.get(0).setFlowState(transReq.getFlowState());
        return baseOwnerInfo;
    }


    @Override
    public BaseOwnerInfo getInfo(String id) {
        return baseOwnerInfoMapper.getInfo(id);
    }

    @Override
    public BaseOwnerInfoMap getInfoMap(String id) {
        return baseOwnerInfoMapper.getInfoMap(id);
    }


    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public synchronized CommonResult insert(List<BaseOwnerInfo> baseOwnerInfoList) {
        String numOwner = ownerNo(baseOwnerInfoList.get(0).getAccNo());
        String ownerId = "";
        for (BaseOwnerInfo baseOwnerInfo : baseOwnerInfoList) {
            baseOwnerInfo.setOwnerNo(numOwner);
            String uuid = UUIDUtil.getUUID();
            if (String.valueOf(NumberEnum.ZERO.getNum()).equals(baseOwnerInfo.getInfoType())) {
                // 查询当前业主是否已经添加过，如果已经添加，则不允许添加业主，只允许添加共有人
                String checkOwner = baseOwnerInfoMapper.checkOwner(baseOwnerInfo);
                if (StringUtils.isNotEmpty(checkOwner)) {
                    return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "该用户业主已经添加，只能添加共有人");
                }
                ownerId = uuid;
                //更新房屋信息表
                updateHouse(baseOwnerInfo);
                //关联附房
                CommonResult houseResult = insertOrUpdateToView(baseOwnerInfo.getBaseOwnerInfoList());
                if (ShiroResultEnum.FAIL.getCode() == houseResult.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), houseResult.getMessage());
                }
            }
            baseOwnerInfo.setCreater(ShiroUserUtil.getUserName());
            baseOwnerInfo.setModifier(ShiroUserUtil.getUserName());
            baseOwnerInfo.setId(uuid);
            baseOwnerInfo.setState(String.valueOf(NumberEnum.ONE.getNum()));
            int num = baseOwnerInfoMapper.insert(baseOwnerInfo);
            if (num == NumberEnum.ZERO.getNum()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            //保存图片
            CommonResult commonResult = fileService.addFile(baseOwnerInfo.getFileTypeList(), uuid);
            if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
            }
        }
        return CommonResult.idResult(NumberEnum.ONE.getNum(), ownerId);
    }

    /**
     * 更新房屋信息表
     *
     * @param baseOwnerInfo 业主信息
     */
    public void updateHouse(BaseOwnerInfo baseOwnerInfo) {
        BaseHouseInfo base = baseHouseInfoMapper.getInfo(baseOwnerInfo.getAccNo());
        if (null != base.getDueState() && !base.getDueState().equals(NumStrEnum.FOUR.getNum())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋已交存不可以修改业主");
        }
        if (null != base.getFlowInProgress() && !NumStrEnum.ZERO.getNum().equals(base.getFlowInProgress())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该房屋存在在途业务不可以修改业主");
        }
        //更新房屋信息表
        BaseHouseInfo baseHouseInfo = new BaseHouseInfo();
        baseHouseInfo.setId(baseOwnerInfo.getAccNo());
        baseHouseInfo.setPrice(baseOwnerInfo.getPrice());
        baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
        baseHouseInfo.setAnnexeArea(baseOwnerInfo.getAnnexeArea());
        baseHouseInfo.setPurchaseDate(baseOwnerInfo.getPurchaseDate());
        //更新房屋信息表
        int num = baseHouseInfoMapper.updateById(baseHouseInfo);
        if (num == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
    }

    @Override
    public PageInfo<BaseModifyDetail> getModifyDetailList(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseModifyDetail> list = baseModifyDetailMapper.getListByReqId(id);
        for (BaseModifyDetail modifyDetail : list) {
            switch (modifyDetail.getColumnName()) {
                case "certType":
                    String oldCertType = modifyDetail.getOldValue();
                    String newCertType = modifyDetail.getNewValue();
                    if (StringUtils.isNotBlank(newCertType)) {
                        newCertType = dicContentMapper.selectName(newCertType);
                    }
                    if (StringUtils.isNotBlank(oldCertType)) {
                        oldCertType = dicContentMapper.selectName(oldCertType);
                    }
                    modifyDetail.setNewValue(null == newCertType ? "" : newCertType);
                    modifyDetail.setOldValue(null == oldCertType ? "" : oldCertType);
                    break;
            }
        }
        PageInfo<BaseModifyDetail> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 业主变更审核
     *
     * @param id      不是业务id
     * @param opinion 意见
     * @param mark    同意/拒绝
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult modifyAudit(String id, String opinion, String mark) {
        int num = NumberEnum.ONE.getNum();
        //查出业主id(不是关联复方的业主id，是主房业主id)
        String business = baseModifyReqMapper.business(id);
        //查询该业主房屋下的所有id
        List<String> bId = baseOwnerInfoMapper.selectHouse(business);
        //插入该业主下的关联付房的id
        List<String> mainId = baseOwnerInfoMapper.selectMain(business);
        if (!mainId.isEmpty()) {
            for (String main : mainId) {
                BaseOwnerInfo b = baseOwnerInfoMapper.getInfoByAccNo(main);
                bId.add(b.getId());
            }
        }
        String auditState = flowUpdateAuditUtil.audit(business, opinion, mark);
        //终审
        if (null != auditState) {
            num = NumberEnum.ONE.getNum();
            //终审成功，修改业务表    其他状态不做处理
            if (FlowStateEnum.PASS.getState().equals(auditState)) {
                //查询出删除的id，调用删除接口，同时删除查出数据中的该id
                List<String> delectId = baseModifyDetailMapper.selectDeleteOwner(id);
                if (delectId.size() != 0) {
                    for (int q = 0; q < delectId.size(); q++) {
                        if (StringUtils.isNotEmpty(delectId.get(q))) {
                            num = baseOwnerInfoMapper.deleteOwner(0, delectId.get(q));
                            if (num == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                            }
                        }
                    }
                }
                List<String> addId = baseModifyDetailMapper.selectAddOwner(id);
                if (addId.size() != 0) {
                    for (int q = 0; q < addId.size(); q++) {
                        if (StringUtils.isNotEmpty(addId.get(q))) {
                            BaseOwnerInfo baseOwnerInfo = new BaseOwnerInfo();
                            baseOwnerInfo.setState(NumStrEnum.ONE.getNum());
                            baseOwnerInfo.setId(addId.get(q));
                            num = baseOwnerInfoMapper.insertOrUpdate(baseOwnerInfo);
                            if (num == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                            }
                        }
                    }
                }
                for (int i = 0; i < bId.size(); i++) {
                    //查询数据库原数据
                    BaseOwnerInfo info = baseOwnerInfoMapper.getInfoById(bId.get(i));
                    if (null == info) {
                        continue;
                    }
                    //变更值合并到原数据   注意参数：uuid变更类型id   info数据库实体
                    List<String> selectBusiness = baseModifyDetailMapper.selectBusiness(id);
                    for (int q = 0; q < selectBusiness.size(); q++) {
                        if (StringUtils.isBlank(selectBusiness.get(q))) {
                            continue;
                        }
                        if (selectBusiness.get(q).equals(bId.get(i))) {
                            BaseOwnerInfo ownerInfo = modifyUtil.getNewCompleteEntity(selectBusiness.get(q), info, id);
                            //全表更新
                            num = baseOwnerInfoMapper.updateById(ownerInfo);
                            BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(info.getAccNo());
                            baseHouseInfo.setPrice(ownerInfo.getPrice());
                            DepModeInfo depModeInfo = depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
                            if ((NumStrEnum.ONE.getNum()).equals(depModeInfo.getDepType())) {
                                baseHouseInfo = changeFirst(baseHouseInfo);
                            }
                            baseHouseInfoMapper.update(baseHouseInfo);
                            if (num == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                            }
                        } else {
                            continue;
                        }
                    }
                }
                //图档更新
                CommonResult result = fileService.dealPassModifyFile(id, business);
                if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
                }
            }
        }
        return CommonResult.ResponseResult(num);
    }

    public BaseHouseInfo changeFirst(BaseHouseInfo baseHouseInfo) {
        baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
        //查看是否足额
        BigDecimal req = accTransactionLogMapper.selectMoneyReqAll(baseHouseInfo.getId());
        BigDecimal dep = accTransactionLogMapper.selectMoneyDepAll(baseHouseInfo.getId());
        BigDecimal money = dep.subtract(req);
        //调用方法看缴存状态
        baseHouseInfo.setDueState(accKeepAccountService.dueStateType(baseHouseInfo, money));
        return baseHouseInfo;
    }

    /**
     * 业主共有人新增或修改
     *
     * @param baseOwnerInfoList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized CommonResult insertOrUpdate(List<BaseOwnerInfo> baseOwnerInfoList) {
        if (baseOwnerInfoList.isEmpty()) {
            return CommonResult.ResponseResult(0, "请选择要添加或修改的信息");
        }
        //当前业主
        String rNo = ownerNo(baseOwnerInfoList.get(0).getAccNo());
        //部分调用没传infotype 需要单独查询
        baseOwnerInfoList.forEach(b -> {
            if (StringUtils.isNotBlank(b.getId()) && StringUtils.isBlank(b.getInfoType())) {
                BaseOwnerInfo info = baseOwnerInfoMapper.getInfo(b.getId());
                b.setInfoType(info.getInfoType());
            }
        });
        //判断是否发生发过缴存
        CommonResult depResult = checkDep(baseOwnerInfoList);
        if (ShiroResultEnum.FAIL.getCode() == depResult.getData()) {
            return depResult;
        }
        //判断是否存在业主id   有业主id则必填业主信息  没有业主id业主信息要么全填、要么全不填
        CommonResult ownerResult = checkOwner(baseOwnerInfoList);
        if (ShiroResultEnum.FAIL.getCode() == ownerResult.getData()) {
            return ownerResult;
        }
        //过滤需要执行操作的记录 业主名不为空的记录
        List<BaseOwnerInfo> list = baseOwnerInfoList.stream().filter(b -> StringUtils.isNotEmpty(b.getName())).collect(Collectors.toList());
        //返回的业主id
        String id = null;
        int num = NumberEnum.ZERO.getNum();
        for (BaseOwnerInfo baseOwnerInfo : list) {
            //赋值
            setBaseOwnerInfo(baseOwnerInfo, rNo);
            if (StringUtils.isBlank(baseOwnerInfo.getPurchaseDate())) {
                baseOwnerInfo.setPurchaseDate(null);
            }
            if (StringUtils.isBlank(baseOwnerInfo.getContractDate())) {
                baseOwnerInfo.setContractDate(null);
            }
            num = baseOwnerInfoMapper.insertOrUpdate(baseOwnerInfo);
            //查询是否有附房业主信息   有的话同时更新
            if (num > 0 && NumStrEnum.ZERO.getNum().equals(baseOwnerInfo.getInfoType())) {
                List<String> subIds = baseOwnerInfoMapper.getIdListByOwnerId(baseOwnerInfo.getId());
                for (String subId : subIds) {
                    updateSubOwnerInfo(baseOwnerInfo, subId);
                }
                id = baseOwnerInfo.getId();
                List<BaseOwnerInfo> baseOwnerList = baseOwnerInfo.getBaseOwnerInfoList();
                if (baseOwnerList != null && !baseOwnerList.isEmpty()) {
                    baseOwnerList.get(0).setOwnerId(id);
                    //关联附房
                    CommonResult result = insertOrUpdateToView(baseOwnerList);
                    if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
                    }
                }
                //处理图片修改
                CommonResult result = fileService.updateFile(baseOwnerInfo.getFileTypeList(), baseOwnerInfo.getId());
                if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
                }
            }
            //业主时修改房屋对应字段
            if (NumStrEnum.ZERO.getNum().equals(baseOwnerInfo.getInfoType())) {
                updateBaseHouseInfo(baseOwnerInfo);
            }

        }
        return CommonResult.idResult(1, id);
    }

    /**
     * 判断是否发生发过缴存
     *
     * @param baseOwnerInfoList 业主集合
     * @return 判断结果
     */
    private CommonResult checkDep(List<BaseOwnerInfo> baseOwnerInfoList) {
        for (BaseOwnerInfo b : baseOwnerInfoList) {
            if (NumStrEnum.ZERO.getNum().equals(b.getInfoType()) && StringUtils.isNotBlank(b.getId())) {
                //是否有审核信息
                int count = flowInstanceMapper.getCountByBusinessId(b.getId());
                if (count > 0) {
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "正在变更业主信息，不允许修改！");
                }
                //是否发生过缴存
                String countDep = depReqLogic.getIsDueState(b.getAccNo());
                if (countDep.equals(NumStrEnum.ONE.getNum())) {
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), "已存在缴存业务，不允许操作，请走业主变更！");
                }
            }
        }
        return CommonResult.ResponseResult(1);
    }

    /**
     * 判断是否存在业主id   有业主id则必填业主信息  没有业主id业主信息要么全填、要么全不填
     *
     * @param baseOwnerInfoList 业主集合
     * @return 判断结果
     */
    private CommonResult checkOwner(List<BaseOwnerInfo> baseOwnerInfoList) {
        //判断是否存在业主id   有业主id则必填业主信息  没有业主id业主信息要么全填、要么全不填
        for (BaseOwnerInfo b : baseOwnerInfoList) {
            if (b.getPrice() == null) {
                b.setPrice(BigDecimal.ZERO);
            }
            BaseHouseInfo info = baseHouseInfoMapper.getInfo(b.getAccNo());
            if (NumStrEnum.ONE.getNum().equals(b.getInfoType())) {
                continue;
            }
            if (StringUtils.isNotEmpty(b.getId())) {
                if (StringUtils.isBlank(b.getState()) || !b.getState().equals(NumStrEnum.ZERO.getNum())) {
                    if (null == b.getPrice() || StringUtils.isEmpty(b.getName()) || StringUtils.isEmpty(b.getCertType()) || StringUtils.isEmpty(b.getCertNo()) || StringUtils.isEmpty(b.getPhone())) {
                        return new CommonResult(ShiroResultEnum.FAIL.getCode(), "请完善： " + info.getHouseSite() + "业主信息！", b.getId());
                    }
                }
            } else {
                if (StringUtils.isBlank(b.getState()) || !b.getState().equals(NumStrEnum.ZERO.getNum())) {
                    if (checkParam(b)) {
                        return new CommonResult(ShiroResultEnum.FAIL.getCode(), "请完善： " + info.getHouseSite() + "业主信息！", b.getId());
                    }
                }
                //有业主信息不允许重复添加
                if (NumStrEnum.ONE.getNum().equals(info.getOwnerState())) {
                    return new CommonResult(ShiroResultEnum.FAIL.getCode(), info.getHouseSite() + "已存在业主信息，请勿重复添加！");
                }
            }
        }
        return CommonResult.ResponseResult(1);
    }

    /**
     * 校验参数
     *
     * @param b 业主信息
     * @return 检验结果
     */
    public boolean checkParam(BaseOwnerInfo b) {
        return !((StringUtils.isEmpty(b.getName()) && StringUtils.isEmpty(b.getCertType()) && StringUtils.isEmpty(b.getCertNo()) && StringUtils.isEmpty(b.getPhone())) ||
                (StringUtils.isNotEmpty(b.getName()) && StringUtils.isNotEmpty(b.getCertType()) && StringUtils.isNotEmpty(b.getCertNo()) && StringUtils.isNotEmpty(b.getPhone())));
    }

    /**
     * 更新附房的业主信息
     *
     * @param baseOwnerInfo
     * @param subId
     * @return
     */
    private int updateSubOwnerInfo(BaseOwnerInfo baseOwnerInfo, String subId) {
        BaseOwnerInfo info = new BaseOwnerInfo();
        info.setId(subId);
        info.setCertNo(baseOwnerInfo.getCertNo());
        info.setCertType(baseOwnerInfo.getCertType());
        info.setPhone(baseOwnerInfo.getPhone());
        info.setName(baseOwnerInfo.getName());
        return baseOwnerInfoMapper.insertOrUpdate(info);
    }

    /**
     * 业主维护时赋值
     *
     * @param baseOwnerInfo
     * @param rNo
     */
    private void setBaseOwnerInfo(BaseOwnerInfo baseOwnerInfo, String rNo) {

        //如果InfoType为空  默认为业主0
        if (StringUtils.isBlank(baseOwnerInfo.getInfoType())) {
            baseOwnerInfo.setInfoType(NumStrEnum.ZERO.getNum());
        }
        //有id为修改  没id为新增
        if (StringUtils.isBlank(baseOwnerInfo.getId())) {
            if (NumStrEnum.ZERO.getNum().equals(baseOwnerInfo.getInfoType())) {
                rNo = ownerNo(baseOwnerInfo.getAccNo());
            }
            baseOwnerInfo.setOwnerNo(rNo);
            String uuid = UUIDUtil.getUUID();
            baseOwnerInfo.setId(uuid);
            baseOwnerInfo.setState(NumStrEnum.ONE.getNum());
            baseOwnerInfo.setCreater(ShiroUserUtil.getUserName());
        } else {
            baseOwnerInfo.setModifier(ShiroUserUtil.getUserName());
            //查询原始数据
            BaseOwnerInfo info = baseOwnerInfoMapper.selectBaseOwnerInfo(baseOwnerInfo.getId());
            //合并实体  注意参数顺序 第一个前端传   第二个数据库原始数据
            baseOwnerInfo = combineEntityUtil.combineEntity(baseOwnerInfo, info);
        }
        baseOwnerInfo.setIsAffiliated(NumStrEnum.ZERO.getNum());
    }

    /**
     * 更新房屋信息
     *
     * @param baseOwnerInfo
     * @return
     */
    private int updateBaseHouseInfo(BaseOwnerInfo baseOwnerInfo) {
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(baseOwnerInfo.getAccNo());
        //把价格添加到房屋表里
        if (null == baseOwnerInfo.getPrice()) {
            baseOwnerInfo.setPrice(BigDecimal.ZERO);
        }
        baseHouseInfo.setPrice(baseOwnerInfo.getPrice());
        if (StringUtils.isNotBlank(baseOwnerInfo.getPurchaseDate())) {
            baseHouseInfo.setPurchaseDate(baseOwnerInfo.getPurchaseDate());
        }
        if (StringUtils.isBlank(baseOwnerInfo.getState())) {
            baseHouseInfo.setState(NumStrEnum.ONE.getNum());
        } else {
            baseHouseInfo.setState(baseOwnerInfo.getState());
        }
        baseHouseInfo.setDueApplyState(NumStrEnum.ZERO.getNum());
        baseHouseInfo.setOwnerState(NumStrEnum.ONE.getNum());
        baseHouseInfo.setPurchaseDate(baseOwnerInfo.getPurchaseDate());
        baseHouseInfo.setFirstDue(calculateAmount.calculateDueAmount(baseHouseInfo));
        return baseHouseInfoMapper.update(baseHouseInfo);
    }

    /**
     * 模糊查询业主信息列表
     *
     * @param page  分页实体
     * @param param 模糊查询参数
     * @return 业主信息
     */
    @Override
    public PageInfo<BaseOwnerFuzzy> fuzzySearch(Page page, String param) {
        String zoneCode = operUtil.getZoneCode();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseOwnerFuzzy> list = baseOwnerInfoMapper.fuzzySearch(zoneCode, param);
        for (BaseOwnerFuzzy b : list) {
            b.setFirstDue(accTransactionLogMapper.selectMoneyDepAll(b.getId()).subtract(accTransactionLogMapper.selectMoneyReqAll(b.getId())));
            b.setExpMoney(accTransactionLogMapper.selectExpByHouseId(b.getId()));
            b.setUseMoney(b.getFunBal().subtract(b.getAccountFrozen()));
        }
        PageInfo<BaseOwnerFuzzy> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 根据房间ID查询业主和共有人
     *
     * @param houseId 房间Id
     * @param arcType 图档类型
     * @return 结果
     */
    @Override
    public List<BaseOwnerInfoMap> getOwnerListByHouseId(String houseId, String arcType) {
        List<BaseOwnerInfoMap> list = baseOwnerInfoMapper.getOwnerListByHouseId(houseId);
        for (BaseOwnerInfoMap baseOwnerInfo : list) {
            if ((NumStrEnum.ZERO.getNum()).equals(baseOwnerInfo.getInfoType())) {
                //查询使用金额
                if (baseOwnerInfo.getFundBal() == null) {
                    baseOwnerInfo.setFundBal(BigDecimal.ZERO);
                }
                if (baseOwnerInfo.getAccrBal() == null) {
                    baseOwnerInfo.setAccrBal(BigDecimal.ZERO);
                }
                if (baseOwnerInfo.getAccountFrozen() == null) {
                    baseOwnerInfo.setAccountFrozen(BigDecimal.ZERO);
                }
                baseOwnerInfo.setAvailableAmount(baseOwnerInfo.getFundBal().add(baseOwnerInfo.getAccrBal()).subtract(baseOwnerInfo.getAccountFrozen()));
                // 查询图档信息
                List<FileVO> fileVOList = fileService.getFileVOList(baseOwnerInfo.getId(), arcType);
                baseOwnerInfo.setFileTypeList(fileVOList);
                //查询附房信息集合
                List<BaseOwnerInfo> subHouseList = getSubHouseList(houseId);
                baseOwnerInfo.setBaseOwnerInfoList(subHouseList);
            }
        }
        return list;
    }

    /**
     * 修改
     *
     * @param newBaseOwnerInfo
     * @param modifyType
     * @param modifyCause
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public synchronized CommonResult updateToSave(List<BaseOwnerInfo> newBaseOwnerInfo, String modifyType, String modifyCause) throws Exception {
        int no = 0;
        //获取关联复方的业主id
        BigDecimal price = BigDecimal.ZERO;
        String uuid = UUIDUtil.getUUID();
        List<BaseOwnerInfo> up = new ArrayList<>();
        List<BaseOwnerInfo> ad = new ArrayList<>();
        //获取新id
        List<String> newId = new ArrayList<>();
        for (int i = 0; i < newBaseOwnerInfo.size(); i++) {
            BaseOwnerInfo baseOwnerInfo = newBaseOwnerInfo.get(i);
            if (NumStrEnum.ZERO.getNum().equals(baseOwnerInfo.getInfoType())) {
                if (null == newBaseOwnerInfo.get(i).getPrice()) {
                    baseOwnerInfo.setPrice(price);
                }
                BigDecimal f = baseOwnerInfo.getPrice();
                DecimalFormat df3 = new DecimalFormat("0.00");
                baseOwnerInfo.setPrice(new BigDecimal(df3.format(f)));

                // 图档变更操作
                fileService.modifyFile(baseOwnerInfo.getFileTypeList(), baseOwnerInfo.getId(), modifyType, modifyCause, uuid);
            }
            newId.add(newBaseOwnerInfo.get(i).getId());
        }
        //获取房屋信息
        String houseNo = newBaseOwnerInfo.get(0).getAccNo();
        //获取业主的编号
        String rNo = baseOwnerInfoMapper.selectOwnerNoForAccNo(houseNo);
        //获取业主id
        String ownerId = baseOwnerInfoMapper.selectOwnerId(houseNo);
        List<BaseOwnerInfo> oldBase = baseOwnerInfoMapper.selectId(houseNo);
        //获取旧id
        List<String> oldId = new ArrayList<>();
        for (int i = 0; i < oldBase.size(); i++) {
            String a = oldBase.get(i).getId();
            oldId.add(a);
        }
        //插入该业主下的关联付房的id
        List<String> mainId = baseOwnerInfoMapper.selectMain(ownerId);
        if (null != mainId) {
            for (String main : mainId) {
                BaseOwnerInfo b = baseOwnerInfoMapper.getInfoByAccNo(main);
                if (null == b.getPrice()) {
                    b.setPrice(BigDecimal.ZERO);
                }
                BigDecimal f = b.getPrice();
                DecimalFormat df3 = new DecimalFormat("0.00");
                b.setPrice(new BigDecimal(df3.format(f)));
                oldId.add(b.getId());
            }
        }

        //查询旧id是否有该数据，若有则修改没有则增加
        for (int i = 0; i < newId.size(); i++) {
            if (oldId.contains(newId.get(i))) {
                BaseOwnerInfo oldBaseOwnerInfo;
                BaseOwnerInfo infoType = baseOwnerInfoMapper.selectInfo(newBaseOwnerInfo.get(i).getId());
                oldBaseOwnerInfo = baseOwnerInfoMapper.selectBaseOwnerInfo(newId.get(i));
                if (null == infoType.getPrice()) {
                    infoType.setPrice(BigDecimal.ZERO);
                }
                if (null == oldBaseOwnerInfo.getPrice()) {
                    oldBaseOwnerInfo.setPrice(BigDecimal.ZERO);
                }
                newBaseOwnerInfo.get(i).setState(oldBaseOwnerInfo.getState());
                newBaseOwnerInfo.get(i).setCreater(oldBaseOwnerInfo.getCreater());
                newBaseOwnerInfo.get(i).setBeginDate(oldBaseOwnerInfo.getBeginDate());
                newBaseOwnerInfo.get(i).setEndDate(oldBaseOwnerInfo.getEndDate());
                newBaseOwnerInfo.get(i).setOwnerNo(oldBaseOwnerInfo.getOwnerNo());
                newBaseOwnerInfo.get(i).setStruArea(null);
                newBaseOwnerInfo.get(i).setHouseUse(null);
                newBaseOwnerInfo.get(i).setAddress(null);
                newBaseOwnerInfo.get(i).setRoomName(null);
                newBaseOwnerInfo.get(i).setFileTypeList((oldBaseOwnerInfo.getFileTypeList()));
                newBaseOwnerInfo.get(i).setHouseSite(oldBaseOwnerInfo.getHouseSite());
                newBaseOwnerInfo.get(i).setFundBal(oldBaseOwnerInfo.getFundBal());
                if (newBaseOwnerInfo.get(i).getInfoType().equals(NumStrEnum.ONE.getNum())) {
                    newBaseOwnerInfo.get(i).setPrice(oldBaseOwnerInfo.getPrice());
                    newBaseOwnerInfo.get(i).setAccrBal(oldBaseOwnerInfo.getAccrBal());
                }
                newBaseOwnerInfo.get(i).setIsAffiliated(oldBaseOwnerInfo.getIsAffiliated());
                if ((NumStrEnum.ONE.getNum()).equals(newBaseOwnerInfo.get(i).getIsAffiliated())) {
                    BaseOwnerInfo exc = new BaseOwnerInfo();
                    BaseOwnerInfo excOld = new BaseOwnerInfo();
                    excOld.setPrice(infoType.getPrice());
                    exc.setPrice(newBaseOwnerInfo.get(i).getPrice());
                    infoType.setRoomName(baseHouseInfoMapper.getInfo(infoType.getAccNo()).getRoomName());
                    no = modifyUtilList.updateToSave(excOld, exc, ownerId, modifyType, modifyCause, uuid, newBaseOwnerInfo.get(i).getId(), infoType);
                } else {
                    no = modifyUtilList.updateToSave(oldBaseOwnerInfo, newBaseOwnerInfo.get(i), ownerId, modifyType, modifyCause, uuid, newBaseOwnerInfo.get(i).getId(), infoType);
                }
                up.add(newBaseOwnerInfo.get(i));
                Iterator<String> itr = oldId.iterator();
                while (itr.hasNext()) {
                    if (itr.next().contains(newId.get(i))) {
                        itr.remove();
                    }
                }
            } else if (!oldId.contains(newId.get(i))) {
                //若新增
                BaseOwnerExc baseOwnerExc = new BaseOwnerExc();
                BaseOwnerExc b = new BaseOwnerExc();
                baseOwnerExc.setName(newBaseOwnerInfo.get(i).getName());
                baseOwnerExc.setPhone(newBaseOwnerInfo.get(i).getPhone());
                baseOwnerExc.setCertType(newBaseOwnerInfo.get(i).getCertType());
                baseOwnerExc.setCertNo(newBaseOwnerInfo.get(i).getCertNo());
                newBaseOwnerInfo.get(i).setCreater(ShiroUserUtil.getUserName());
                newBaseOwnerInfo.get(i).setState(NumStrEnum.ZERO.getNum());
                newBaseOwnerInfo.get(i).setOwnerNo(rNo);
                newBaseOwnerInfo.get(i).setId(UUIDUtil.getUUID());
                no = baseOwnerInfoMapper.insertOrUpdate(newBaseOwnerInfo.get(i));
                if (no == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                }
                BaseOwnerInfo infoType = baseOwnerInfoMapper.selectInfo(newBaseOwnerInfo.get(i).getId());
                no = modifyUtilList.updateToSave(b, baseOwnerExc, ownerId, modifyType, modifyCause, uuid, newBaseOwnerInfo.get(i).getId(), infoType);
                ad.add(newBaseOwnerInfo.get(i));
            }
        } //删除
        if (oldId.size() != 0) {
            for (int i = 0; i < oldId.size(); i++) {
                BaseOwnerExc baseOwnerExc = new BaseOwnerExc();
                BaseOwnerExc base = new BaseOwnerExc();
                baseOwnerExc.setName("");
                baseOwnerExc.setPhone("");
                baseOwnerExc.setCertType("");
                baseOwnerExc.setCertNo("");
                BaseOwnerInfo oldBaseOwnerInfo = baseOwnerInfoMapper.getInfoById(oldId.get(i));
                baseOwnerExc.setName(oldBaseOwnerInfo.getName());
                baseOwnerExc.setPhone(oldBaseOwnerInfo.getPhone());
                baseOwnerExc.setCertType(oldBaseOwnerInfo.getCertType());
                baseOwnerExc.setCertNo(oldBaseOwnerInfo.getCertNo());
                BaseOwnerInfo infoType = baseOwnerInfoMapper.selectInfo(oldId.get(i));
                no = modifyUtilList.updateToSave(baseOwnerExc, base, ownerId, modifyType, modifyCause, uuid, oldId.get(i), infoType);
            }
        }
        int b = baseModifyDetailMapper.selectCountByReqNo(uuid);
        if (b == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败请检查变更数据");
        }
        String initState = flowUpdateAuditUtil.initFlow(ownerId, uuid, modifyType, null);
        //当返回通过时表明该记录不需要审核，直接更新到业务表
        if (FlowStateEnum.PASS.getState().equals(initState)) {
            if (up.size() != 0) {
                for (int j = 0; j < up.size(); j++) {
                    //查询数据库原数据
                    BaseOwnerInfo info = baseOwnerInfoMapper.getInfoById(up.get(j).getId());
                    info.setFlowState(NumStrEnum.TWO.getNum());
                    info.setState(NumStrEnum.ONE.getNum());
                    if (info.getInfoType().equals(NumStrEnum.ZERO.getNum())) {
                        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(info.getAccNo());
                        baseHouseInfo.setPrice(up.get(j).getPrice());
                        DepModeInfo depModeInfo = depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
                        //修改初交应交的金额
                        if ((NumStrEnum.ONE.getNum()).equals(depModeInfo.getDepType())) {
                            baseHouseInfo = changeFirst(baseHouseInfo);
                        }
                        no = baseHouseInfoMapper.update(baseHouseInfo);
                        if (no == NumberEnum.ZERO.getNum()) {
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                        }
                    }
                    //变更值合并到原数据   注意参数：uuid变更类型id   info数据库实体
                    List<String> selectBusiness = baseModifyDetailMapper.selectBusiness(uuid);
                    for (int q = 0; q < selectBusiness.size(); q++) {
                        if (StringUtils.isBlank(selectBusiness.get(q))) {
                            continue;
                        }
                        if (selectBusiness.get(q).equals(up.get(j).getId())) {
                            BaseOwnerInfo ownerInfo = modifyUtil.getNewCompleteEntity(selectBusiness.get(q), info, uuid);
                            //全表更新
                            no = baseOwnerInfoMapper.updateById(ownerInfo);
                            if (no == 0) {
                                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败");
                            }
                        } else {
                            continue;
                        }
                    }
                }
            }
            //删除
            if (oldId.size() != 0) {
                for (int j = 0; j < oldId.size(); j++) {
                    no = baseOwnerInfoMapper.deleteOwner(0, oldId.get(j));
                    if (no == 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                    }
                }
            }
            if (ad.size() != 0) {
                for (int j = 0; j < ad.size(); j++) {
                    ad.get(j).setModifier(ShiroUserUtil.getUserName());
                    ad.get(j).setState(NumStrEnum.ONE.getNum());
                    ad.get(j).setFlowState(NumStrEnum.TWO.getNum());
                    no = baseOwnerInfoMapper.insertOrUpdate(ad.get(j));
                    if (no == 0) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "变更失败，请重新操作");
                    }
                }
            }
            //图档更新
            CommonResult result = fileService.dealPassModifyFile(uuid, ownerId);
            if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
            }
        }
        return CommonResult.ResponseResult(no);
    }

    /**
     * 生成业主账号的方法
     *
     * @param houseId
     * @return
     */
    @Override
   public synchronized String ownerNo(String houseId) {
        BigInteger ownerNum;
        BigInteger add = new BigInteger(NumStrEnum.ONE.getNum());
        String rNo = "";
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(houseId);
        String buildId = "";
        if (null == baseHouseInfo) {
            buildId = splitMergeReqDetailMapper.selectBuildNoByHouseId(houseId);
            if (StringUtils.isBlank(buildId)) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "未查询到自然幢id");
            }
        } else {
            buildId = baseHouseInfo.getBuildNo();
        }
        String houseIds = baseOwnerInfoMapper.selectAllHouseId(buildId);
        if (null == baseHouseInfo) {
            houseIds = houseIds + "," + houseId;
        }
        String ownerNo = baseOwnerInfoMapper.selectMaxOwner(houseIds);
        String buildNo = baseBuildInfoMapper.selectBuildNoFromid(buildId);
        if (StringUtils.isBlank(ownerNo)) {
            ownerNo = NumStrEnum.ZERO.getNum();
            ownerNum = new BigInteger(ownerNo);
            rNo = NumStrEnum.THREE.getNum() + buildNo + String.format("%03d", ownerNum);
        } else {
            if (baseHouseInfo == null) {
                List<BaseOwnerInfo> list = baseOwnerInfoMapper.selectId(houseId);
                for (BaseOwnerInfo b : list) {
                    b.getAccNo();
                }
            }
            ownerNum = new BigInteger(ownerNo);
            ownerNum = ownerNum.add(add);
            rNo = String.format("%03d", ownerNum);
        }
        return rNo;
    }
}




